package com.ipartek.dadoweb.filtros;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class LogedUsserFilter
 */
public class LogedUsserFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public LogedUsserFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	@Override
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		String path = ((HttpServletRequest) request).getRequestURI();
		HttpServletRequest httpreq = (HttpServletRequest) request;

		if (httpreq.getSession().getAttribute("isMobile") == "F") {
			ArrayList<String> disallowedPath = new ArrayList<String>();
			disallowedPath.add("/movil");
			disallowedPath.add("/historia.jsp");

			boolean encontrado = false;

			for (int i = 0; i < disallowedPath.size(); i++) {
				if (path.contains(disallowedPath.get(i))) {
					encontrado = true;
				}
			}

			if (encontrado == false) {
				if (httpreq.getSession().getAttribute("username") == null) {
					request.getRequestDispatcher("/login").forward(request,
							response);
				}
			}
		}

		chain.doFilter(request, response); // Just continue chain.
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
